# coding: utf-8
from flask import Flask, render_template, flash, redirect, url_for, jsonify
from sqlalchemy.sql import func,and_
from flask_bootstrap import Bootstrap
from config import load_config
from Model.Depts import db, DeptTree
from form import *
from Model.satree import TreeManager

app = Flask(__name__)
bs = Bootstrap()
app.config.from_object(load_config())
db.init_app(app)
bs.init_app(app)


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/Depout.json')
def Depoutjson():
    # 节点数据
    to = []
    tmp = DeptTree.query
    for item in tmp:
        to.append(
            {"node_id": item.node_id, "dept_name": item.dept_name, "sys_id": item.sys_id, "parent_id": item.parent_id})
    # to = tm.output(output_err=True,flatted=True)
    print(to)
    return jsonify(to)


@app.route('/list')
def list():
    return render_template("list.html")

@app.route('/p')
def potato():
    return render_template("potato.html")

@app.route('/add', methods=('GET', 'POST'))
def add():
    node_id = None
    dept_name = None
    sys_id = None
    parent_id = None
    form = AddNode()
    tm = TreeManager(DeptTree, db.session)
    if form.validate_on_submit():
        node_id = form.node_id.data
        dept_name = form.dept_name.data
        sys_id = form.sys_id.data
        parent_id = form.parent_id.data
        # 本节点数据
        dept_tree_item = DeptTree.query.filter_by(node_id=node_id).first()
        # 上级节点数据
        if parent_id is None:
            ref_node = None
        else:
            ref_node = DeptTree.query.filter_by(node_id=parent_id).first()
        if ref_node is None:
            ref_node_id = ""
        else:
            ref_node_id = ref_node.node_id
        node = DeptTree(node_id=node_id, dept_name=dept_name, sys_id=sys_id, parent_id=ref_node_id,
                        is_sys=(0 if sys_id is None else 1))
        tm.add_node(nodes=node, ref_node=ref_node, tree_id=1)
        # 保存提交到数据库
        db.session.commit()
        db.session.close()
        return redirect(url_for('list'))
    return render_template("add.html", form=form)



if __name__ == '__main__':
    app.run()
